package com.scisoft.scan.control.stock;

import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.data.depot.WarehouseBean;
import com.scisoft.scan.data.stock.StockFlowQueryBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.data.stock.StockFlowBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper_Depot;
import com.scisoft.scan.ws.WebServiceHelper_Stock;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class StockFlowQueryActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private TextView tv_query;
    private TextView tv_cancel;
    private ClearEditText et_partNo;
    private Spinner spin_depot;
    private TextView et_startDate;
    private TextView et_stopDate;
    private ClearEditText et_gys;

    private List<String> depotList = new ArrayList<>();
    private List<WarehouseBean> depotBeanList = new ArrayList<WarehouseBean>();
    private int selectedDepotNo = 0;

    private StockFlowQueryBean stockFlowQueryBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_stock_flow_query);

        et_partNo = findViewById(R.id.et_partNo);
        //日期控件
        Calendar calendar = Calendar.getInstance();//调用Calendar类获取年月日

        et_startDate = findViewById(R.id.et_startDate);
        final int mYear1 = calendar.get(Calendar.YEAR);//年
        final int mMonth1 = calendar.get(Calendar.MONTH) + 1;//月份要加一个一，这个值的初始值是0。不加会日期会少一月。
        final int mDay1 = 1;//日
        et_startDate.setText(mYear1 + "-" + String.format("%02d", mMonth1) + "-" + String.format("%02d", mDay1));
        et_startDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatePickerDialog datePickerDialog = new DatePickerDialog(StockFlowQueryActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        et_startDate.setText(i + "-" + String.format("%02d", i1 + 1) + "-" + String.format("%02d", i2));
                    }
                }, mYear1, mMonth1 - 1, mDay1);//将年月日放入DatePickerDialog中，并将值传给参数

                datePickerDialog.show();//显示dialog
            }
        });

        et_stopDate = findViewById(R.id.et_stopDate);
        final int mYear2 = calendar.get(Calendar.YEAR);//年
        final int mMonth2 = calendar.get(Calendar.MONTH) + 1;//月份要加一个一，这个值的初始值是0。不加会日期会少一月。
        final int mDay2 = calendar.get(Calendar.DAY_OF_MONTH);//日
        et_stopDate.setText(mYear2 + "-" + String.format("%02d", mMonth2) + "-" + String.format("%02d", mDay2));
        et_stopDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatePickerDialog datePickerDialog = new DatePickerDialog(StockFlowQueryActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        et_stopDate.setText(i + "-" + String.format("%02d", i1 + 1) + "-" + String.format("%02d", i2));
                    }
                }, mYear2, mMonth2 - 1, mDay2);//将年月日放入DatePickerDialog中，并将值传给参数

                datePickerDialog.show();//显示dialog
            }
        });
        et_gys = findViewById(R.id.et_gys);
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StockFlowQueryActivity.this, MainMenuActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        //查询
        tv_query = findViewById(R.id.tv_query);
        tv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //校验
                getData();
                if (stockFlowQueryBean.partNo == null || stockFlowQueryBean.partNo.length() == 0) {
                    Toast.makeText(StockFlowQueryActivity.this, "请先扫描配件", Toast.LENGTH_LONG).show();
                    return;
                }
                CommonUtil.showPress(StockFlowQueryActivity.this);
                QueryFlowTask queryFlowTask = new QueryFlowTask(StockFlowQueryActivity.this);
                queryFlowTask.execute();
            }
        });
        //取消
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StockFlowQueryActivity.this, MainMenuActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        //仓库
        spin_depot = findViewById(R.id.spin_depot);
        QueryWarehouseTask queryWarehouseTask = new QueryWarehouseTask(StockFlowQueryActivity.this);
        queryWarehouseTask.execute();
    }

    private void getData() {
        stockFlowQueryBean = new StockFlowQueryBean();
        stockFlowQueryBean.partNo = et_partNo.getUpperText().toString();
        stockFlowQueryBean.manufacturerName = et_gys.getUpperText().toString();
        stockFlowQueryBean.depotId = "0";
        if (selectedDepotNo >= 0 && selectedDepotNo < depotBeanList.size()) {
            stockFlowQueryBean.depotId = depotBeanList.get(selectedDepotNo).depotId;
        }
        stockFlowQueryBean.startDate = et_startDate.getText().toString();
        stockFlowQueryBean.endDate = et_stopDate.getText().toString();
    }

    //查询库存流水
    class QueryFlowTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private StockFlowBean stockFlowBean;

        QueryFlowTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                stockFlowBean = WebServiceHelper_Stock.STOCK_02(stockFlowQueryBean);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Intent intent = new Intent(StockFlowQueryActivity.this, StockFlowActivity.class);
                intent.putExtra("data", stockFlowBean);
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //绑定仓库数据
    private void SetSpanDepot(Context context) {
        spin_depot = findViewById(R.id.spin_depot);
        for (int i = 0; i < depotBeanList.size(); i++) {
            depotList.add(depotBeanList.get(i).depotName);
        }
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, depotList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_depot.setAdapter(adapter2);
        spin_depot.setSelection(0, true);
        spin_depot.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDepotNo = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //查询仓库服务
    class QueryWarehouseTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryWarehouseTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                depotBeanList = WebServiceHelper_Depot.DEPOT_01();
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                SetSpanDepot(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }


    //以下为扫码相关
    private ScanManager mScanMgr = null;//扫码接口

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        registerReceiver(mResultReceiver, intFilter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ScanManager.ACTION_SEND_SCAN_RESULT.equals(action)) {
                byte[] bvalue1 = intent.getByteArrayExtra(ScanManager.EXTRA_SCAN_RESULT_ONE_BYTES);
                String svalue1 = null;
                try {
                    if (bvalue1 != null) {
                        svalue1 = new String(bvalue1, "GBK");
                        BarCodeBean barCodeBean = CommonUtil.ParseBarCodeNew(StockFlowQueryActivity.this, svalue1);
                        if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                            Toast.makeText(StockFlowQueryActivity.this, "无效二维码：" + svalue1, Toast.LENGTH_LONG).show();
                        } else if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                            //配件
                            PartBean partBean = barCodeBean.partBean;
                            et_partNo.setText(partBean.partCode);
                        } else if (barCodeBean.barType == BarCodeBean.BAR_SHELVES) {
                            Toast.makeText(StockFlowQueryActivity.this, "请扫描配件", Toast.LENGTH_LONG).show();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(StockFlowQueryActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
}
